#!/bin/sh

# 获取系统语言环境 | Get system locale
LANG=$(locale | grep LANGUAGE | cut -d '=' -f 2 | cut -d '_' -f 1)

# 翻译文本 | Translation variables
readonly TIP_zh="即将初始化 NVIDIA 显卡相关配置文件......"
readonly TIP_en="Preparing to initialize configs related to NVIDIA graphics..."

eval "TIP=\$TIP_${LANG}"

# 提示文字 | Tip
echo $TIP

# 获取显卡 BusID | Get device BusID
# 仅获取第一张 NVIDIA 显卡的 PCI 设备地址 | Only get the first device BusID
NVIDIA_BusID=`lspci | egrep 'VGA|3D' | grep 'NVIDIA' | cut -d ' ' -f 1 | sed -r 's/0?(.)/\1/' | sed -e 's/:0/:/g' -e 's/\./:/g' | head -n 1`

Intel_BusID=`lspci | egrep 'VGA|3D' | grep 'Intel' | cut -d ' ' -f 1 | sed -r 's/0?(.)/\1/' | sed -e 's/:0/:/g' -e 's/\./:/g'`

# 生成 xorg.conf | Generate xorg.conf
echo '# dde-dock-graphics-plugin: X configuration file generated by dde-dock-plugins
# dde-dock-graphics-plugin: version 1.8.2

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    Option         "AllowNVIDIAGPUScreens"
EndSection

Section "Module"
	Load "modesetting"
EndSection

Section "Device"
    Identifier     "GFX0"
    Driver         "modesetting"
    VendorName     "Intel Corporation"
    BusID          "PCI:'$Intel_BusID'"
EndSection

Section "Device"
    Identifier     "PEGP"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BusID          "PCI:'$NVIDIA_BusID'"
EndSection

Section "Screen"
    Identifier     "IGPU"
    Device         "GFX0"
    DefaultDepth    24
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Section "Screen"
    Identifier     "DGPU"
    Device         "PEGP"
    DefaultDepth    24
    Option         "AllowEmptyInitialConfiguration"
    SubSection     "Display"
        Depth       24
    EndSubSection
    Option         "Coolbits" "28"
EndSection' | sudo tee /etc/X11/xorg.conf.bak > /dev/null

# 生成 nvidia-graphics-drivers.conf | Generate nvidia-graphics-drivers.conf
echo 'options nvidia-drm modeset=1' | sudo tee /etc/modprobe.d/nvidia-graphics-driver.conf.bak > /dev/null

# 生成 display_setup.sh | Generate display_setup.sh
echo '#!/bin/sh
xrandr --setprovideroutputsource modesetting NVIDIA-0
xrandr --auto
xrandr --dpi 96' | sudo tee /etc/lightdm/display_setup.sh > /dev/null
sudo chmod +x /etc/lightdm/display_setup.sh
